package org.mcache;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author: tjc
 * @description
 * @Date Created in 10:24 2022-08-07
 */
public class RedisDict extends RedisObject {

    Map<RedisString, RedisObject> impl = new HashMap<>();

    public RedisObject get(RedisString key) {
        return impl.get(key);
    }

    public void put(RedisString key, RedisObject value) {
        impl.put(key, value);
    }

    public RedisObject remove(RedisString key) {
//        return (int) Arrays.stream(keys).filter(key -> impl.remove(key) != null).count();
        return impl.remove(key);
    }

//    public RedisString getString(RedisString key) {
//        return impl.get(key).checkRedisString();
//    }

    public boolean contains(RedisString key) {
        return impl.containsKey(key);
    }

    @Override
    public boolean isRedisDict() {
        return true;
    }

    @Override
    public RedisDict checkRedisDict() {
        return this;
    }

    public Collection<RedisObject> values() {
        return impl.values();
    }

    public static class DictEntry {
        private RedisString key;
        private RedisObject value;

        public DictEntry(RedisString key, RedisObject value) {
            this.key = key;
            this.value = value;
        }

        public RedisString getKey() {
            return key;
        }

        public void setKey(RedisString key) {
            this.key = key;
        }

        public RedisObject getValue() {
            return value;
        }

        public void setValue(RedisObject value) {
            this.value = value;
        }
    }

    class DictIterator implements Iterator<DictEntry> {
        Iterator<Map.Entry<RedisString, RedisObject>> iter;

        public DictIterator() {
            iter = impl.entrySet().iterator();
        }

        @Override
        public boolean hasNext() {
            return iter.hasNext();
        }

        @Override
        public DictEntry next() {
            Map.Entry<RedisString, RedisObject> next = iter.next();
            return new DictEntry(next.getKey(), next.getValue());
        }

        @Override
        public void remove() {
            iter.remove();
        }
    }

    public Iterator<DictEntry> iterator() {
        return new DictIterator();
    }

}
